﻿using StarPizza.Model.BaseModel;
using StarPizza.Model.Core;
using StarPizza.Model.User;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace StarPizza.Model.Ordering
{
    class OrderHistory
    {
        StarDataDataContext db;
        UserSpace userSpace;
        public const int ORDERED_PIZZA_INFO_START_IDX = 1;
        public OrderHistory(StarDataDataContext db, UserSpace userSpace)
        {
            this.db = db;
            this.userSpace = userSpace;
        }
        private StarPizza.Model.BaseModel.OrderedPizzaInfo CreateOrderedPizzaInfo(IPizza pizza, int pizzaIdx)
        {
            var refID = pizza.PizzaTemplate.ReferencableID;
            var info = new OrderedPizzaInfo
            {
                PizzaIndex = pizzaIdx,
                Size = pizza.Size,
                Price = pizza.Price
            };
            if (refID == null)
            {
                info.PizzaTemplateID = refID;
            }
            else
            {
                info.PizzaTemplate = db.PizzaTemplate
                    .Where(pizzaTemplate => pizzaTemplate.ID == refID).First();
            }
            return info;
        }
        private OrderInfo CreateOrderInfo(IEnumerable<IPizza> orderedPizzas)
        {
            var orderInfo = new OrderInfo
            {
                Client = userSpace.LoggedInClient,
                OrderDate = DateTime.Now
            };
            int pizzaIdx = ORDERED_PIZZA_INFO_START_IDX;
            foreach (var pizza in orderedPizzas)
            {
                orderInfo.OrderedPizzaInfo.Add(CreateOrderedPizzaInfo(pizza, pizzaIdx));
                ++pizzaIdx;
            }
            return orderInfo;
        }
        public void SaveOrderInfo(IEnumerable<IPizza> orderedPizzas) 
        {
            var orderInfo = CreateOrderInfo(orderedPizzas);
            db.OrderInfo.InsertOnSubmit(orderInfo);
            Utility.TrySubmitChanges(db);
        }
        public IQueryable<OrderedPizzaInfo> GetOrderedPizzasBetween(DateTime startDate, DateTime endDate)
        {
            return db.OrderedPizzaInfo.Where(OrderedPizzaInfo.IsOrderDateBetween(startDate, endDate));
        }
    }
}
